class MixlyNavGenerator {
    constructor(navId, type, navConfig, thirdPartyBoard) {
        this._navId = navId;
        this._type = type;
        this._config = this.getConfig(navConfig);
        this._thirdPartyBoard = thirdPartyBoard;
    }

    getConfig(navConfig) {
        let defaultSetting = {
            "thirdPartyLibrary": false
        }

        let defaultSave = {
            "ino": false,
            "bin": false,
            "hex": false,
            "py": false,
            "img": false
        }

        let defaultNav = {
            "burn": false,
            "upload": false,
            "compile": false,
            "simulate": false,
            "run": false,
            "cancel": false,
            "save": defaultSave,
            "setting": defaultSetting
        }

        let _config = {};

        for (let key in defaultNav) {
            if (typeof defaultNav[key] === "object") {
                if (navConfig[key] === undefined) {
                    _config[key] = defaultNav[key];
                } else {
                    _config[key] = {};
                    for (let childKey in defaultNav[key]) {
                        _config[key][childKey] = navConfig[key][childKey] ?? defaultNav[key][childKey];
                    }
                }
            } else {
                _config[key] = navConfig[key] ?? defaultNav[key];
            }
        }

        return _config;
    }

    init() {
        let navDom = document.getElementById(this._navId);

        let {
            burn,
            compile,
            upload,
            simulate,
            save,
            run,
            cancel,
            setting
        } = this._config;

        if (!MixlyEnv.isClient && MixlyUrl.BOARD_CONFIG?.boardName == "MixGo AI") {
            burn = false;
        }

        let {
            ino,
            bin,
            hex,
            py,
            img
        } = save;

        let {
            thirdPartyLibrary
        } = setting;

        let _fileOperateBtn = "";
        if (MixlyEnv.isClient) {
            _fileOperateBtn = `<dd lay-unselect>
                                    <a href="#" id="save_btn" class="icon-floppy" onclick="MixlyFile.saveFile()"></a>
                                </dd>
                                <dd lay-unselect>
                                    <a href="#" id="save_as_btn" class="icon-floppy" onclick="MixlyFile.saveAs(null, indexText['另存为'], '')"></a>
                                </dd>`;
        } else {
            _fileOperateBtn = `<dd lay-unselect>
                                    <a href="#" id="save_xml_btn" class="icon-floppy" onclick="${this._type ? 'MixlyFile.saveMix();' : 'save();'}"></a>
                                </dd>
                                ${py ? 
                                `<dd lay-unselect>
                                    <a href="#" id="save_py_btn" class="icon-file-code" onclick="${this._type ? 'MixlyFile.savePy();' : 'mixlyjs.savePyFileAs();'}"></a>
                                </dd>`
                                : ''}
                                ${ino ? 
                                `<dd lay-unselect>
                                    <a href="#" id="save_ino_btn" class="icon-file-code" onclick="${this._type ? 'MixlyFile.saveIno();' : 'mixlyjs.saveInoFileAs();'}"></a>
                                </dd>`
                                : ''}
                                ${(!compile && hex) ? 
                                `<dd lay-unselect>
                                    <a href="#" id="save_hex_btn" class="icon-file-code" onclick="${this._type ? 'MixlyFile.saveHex()' : 'mixlyjs.compileMicrobitPy();'}"></a>
                                </dd>`
                                : ''}
                                ${img ? 
                                `<dd lay-unselect>
                                    <a href="#" id="save_img_btn" class="icon-floppy" onclick="${this._type ? 'MixlyFile.saveImg();' : 'mixlyjs.saveBlockImg();'}"></a>
                                </dd>`
                                : ''}
                                ${this._type ? 
                                `<dd lay-unselect>
                                    <a href="#" id="save_as_btn" class="icon-floppy" onclick="MixlyFile.saveAs(null, indexText['另存为'], '')"></a>
                                </dd>`
                                : ''}`;
        }

        let _navOperateBtn = `
        <dd lay-unselect>
            <a href="#" onclick="UndoClick();" name="undo" id="operate_undo_btn" title="undo(ctrl+z)" class="icon-ccw"></a>
        </dd>
        <dd lay-unselect><a href="#" onclick="RedoClick();" name="redo" id="operate_redo_btn" title="redo(ctrl+y)" class="icon-cw">重复</a>
        </dd>
        ${(!this._type) ? //显示网页版串口连接
        `<dd lay-unselect>
            <a href="#" onclick="MixlyWebBU.clickConnect()" id="operate_connect_btn" class="icon-link">连接</a>
        </dd>`
        : ''}
        ${burn ? //显示固件初始化按钮
        `<dd lay-unselect>
            <a href="#" onclick="MixlyBU.initBurn();" id="operate_serial_reset" class="icon-upload-1">初始化固件</a>
        </dd>` 
        : ''}
        ${compile ? //显示编译按钮
        `<dd lay-unselect>
            <a href="#" onclick="MixlyArduino.initCompile();" id="operate_arduino_compile" class="icon-check">编译</a>
        </dd>`
        : ''}
        ${(compile && upload) ? //显示Arduino上传按钮
        `<dd lay-unselect>
            <a href="#" onclick="MixlyArduino.initUpload();" id="operate_download_btn" class="icon-upload">上传</a>
        </dd>`
        : ''}
        ${(!compile && upload) ? //显示py上传按钮
        `<dd lay-unselect>
            <a href="#" onclick="MixlyBU.initUpload();" id="operate_download_btn" class="icon-upload">上传</a>
        </dd>`
        : ''}
        ${simulate ? //显示仿真按钮
        `<dd lay-unselect>
            <a href="#" onclick="MixlyAvrSimulate.initSimulate();" id="operate_simulate_btn" class="icon-play-circled">仿真</a>
        </dd>`
        : ''}
        ${(run || cancel)?
        `<dd lay-unselect>
            <a href="#" onclick="MixlyPython.play();" id="operate_play_btn" class="icon-play-circled">运行</a>
        </dd>
        <dd lay-unselect>
            <a href="#" onclick="MixlyPython.stop();" id="operate_stop_btn" class="icon-cancel">取消</a>
        </dd>`
        : 
        `<dd lay-unselect>
            <a href="#" onclick="MixlySerial.init();" id="operate_serial_read_btn" class="icon-link">串口</a>
        </dd>`}
        <dd lay-unselect>
            <a href="#" onclick="MixlyStatusBar.show(0);" id="operate_layer_btn" class="icon-window">状态栏</a>
        </dd>`;
        
        let _navStr = `
        <li class="layui-nav-item" lay-unselect>
            <a id="mixly-path" href="${this._thirdPartyBoard ? '../' : ''}../../index.html">Mixly</a>
        </li>
        <li style="display:none" id="tab_blocks" lay-unselect></li>
        <li style="display:none" id="tab_arduino" lay-unselect></li>
        <li style="display:none" id="tab_xml"></li>
        <li class="layui-nav-item" id="li_operate" style="display:none;" lay-unselect>
            <a href="javascript:;" id="operate_btn">
                <span class="layui-nav-more"></span>
            </a>
            <dl class="layui-nav-child">
                <!-- 二级菜单 -->
                ${_navOperateBtn}
            </dl>
        </li>
        <li class="layui-nav-item" id="li_undo" lay-unselect>
            <a href="#" onclick="UndoClick();" name="undo" id="undo_btn" title="undo(ctrl+z)" class="icon-ccw"></a>
        </li>
        <li class="layui-nav-item" id="li_redo" lay-unselect>
            <a href="#" onclick="RedoClick();" name="redo" id="redo_btn" title="redo(ctrl+y)" class="icon-cw"></a>
        </li>
        ${(!this._type) ? 
        `<li class="layui-nav-item" id="li_connect" style="display:none;" lay-unselect>
            <a href="#" onclick="MixlyWebBU.clickConnect()" id="connect_btn" class="icon-link"></a>
        </li>`
        : ''}
        ${burn ? 
        `<li class="layui-nav-item" id="li_serial_reset" lay-unselect>
            <a href="#" onclick="MixlyBU.initBurn();" id="serial_reset" class="icon-upload-1" ></a>
        </li>`
        : ''}
        ${compile ? 
        `<li class="layui-nav-item" id="li_arduino_compile" lay-unselect>
            <a href="#" onclick="MixlyArduino.initCompile();" id="arduino_compile_btn" class="icon-check" ></a>
        </li>`
        : ''}
        ${(compile && upload) ? 
        `<li class="layui-nav-item" id="li_download" lay-unselect>
            <a href="#" onclick="MixlyArduino.initUpload();" id="arduino_download_btn" class="icon-upload" ></a>
        </li>`
        : ''}
        ${(!compile && upload) ? 
        `<li class="layui-nav-item" id="li_download" lay-unselect>
            <a href="#" id="download_btn" onclick="MixlyBU.initUpload();" class="icon-upload" ></a>
        </li>`
        : ''}
        ${simulate ? 
        `<li class="layui-nav-item" id="li_simulate" lay-unselect>
            <a href="#" id="simulate_btn" onclick="MixlyAvrSimulate.initSimulate();" class="icon-play-circled" ></a>
        </li>`
        : ''}
        ${(run || cancel)?
        `<li class="layui-nav-item" id="li_play" lay-unselect>
            <a href="#" name="run" onclick="MixlyPython.play();" id="play_btn" class="icon-play-circled">
            </a>
        </li>
        <li class="layui-nav-item" id="li_stop" lay-unselect>
            <a href="#" name="stop" onclick="MixlyPython.stop();" id="stop_btn" class="icon-cancel">
            </a>
        </li>`:
        `<li class="layui-nav-item" id="li_serial_read" lay-unselect>
            <a href="#" id="serial_read_btn" onclick="MixlySerial.init();" class="icon-link" ></a>
        </li>`}
        <li class="layui-nav-item" id="li_layer" lay-unselect>
            <a href="#" id="layer_btn" class="icon-window" onclick="MixlyStatusBar.show(0);"></a>
        </li>
        <a id="copyright"></a>
        <li class="layui-nav-item" style="float:right" lay-unselect>
            <a href="javascript:;" id="setting_btn"></a>
            <dl class="layui-nav-child">
                <!-- 二级菜单 -->
                <dd lay-unselect>
                    <a href="#" id="language_btn" class="icon-language" onclick="open_language(); "></a>
                </dd>
                <dd lay-unselect>
                    <a href="#" id="theme_btn" class="icon-art-gallery" onclick="open_theme();"></a>
                </dd>
                <dd lay-unselect>
                    <a href="#" id="changemod_btn" class="icon-code" value=1 onclick="changeMod();"></a>
                </dd>
                ${(this._type && thirdPartyLibrary) ? 
                `<dd lay-unselect>
                    <a href="#" id="import_libraries_btn" class="icon-download" onclick="open_lib();"></a>
                </dd>
                <dd lay-unselect>
                    <a href="#" id="manage_libraries_btn" class="icon-menu" onclick="manageLibraries();"></a>
                </dd>`
                : ''}
                ${(this._type) ? 
                    `<dd lay-unselect>
                        <a href="#" id="windows_size_btn" class="icon-popup" onclick="open_winsize();"></a>
                    </dd>`
                    : ''}
            </dl>
        </li>
        <li class="layui-nav-item" style="float:right" lay-unselect>
            <a href="javascript:;" id="file_btn"></a>
            <dl class="layui-nav-child">
                <!-- 二级菜单 -->
                <dd lay-unselect>
                    <a href="#" onclick="${this._type ? 'MixlyFile.newFile();' : 'new_file();'}" id="new_btn" class="icon-doc-new"></a>
                </dd>
                <dd lay-unselect>
                    <a href="#" onclick="${this._type ? 'MixlyFile.loadFile();' : 'loadFile();'}" id="open_btn" class="icon-folder-open-empty"></a>
                </dd>
                ${_fileOperateBtn}
            </dl>
        </li>
        <li class="layui-nav-item" lay-unselect>
            <select id="languageMenu" style="display:none">
            </select>
        </li>
        `;

        navDom.innerHTML = _navStr;
    }
}

function navInit() {
    let isClient =  MixlyEnv.isClient;
    let navConfig = MixlyUrl.BOARD_CONFIG?.nav ?? {};
    let thirdPartyBoard = MixlyUrl.BOARD_CONFIG?.thirdPartyBoard ?? false;
    let navObj = new MixlyNavGenerator("nav", isClient, navConfig, thirdPartyBoard);
    navObj.init();
}

navInit();
/*
layui.config({
    base: MixlyUrl?.BOARD_CONFIG?.thirdPartyBoard ? '../../common/layui/lay/extend/' : '../common/layui/lay/extend/'
}).extend({
    dropdown: 'dropdown'
}).use(['dropdown', 'tree'], function (dropdown, tree) {
    // treeselect
    var $input2 = $('#boardSelector .layui-input');
    var instance2 = dropdown.render({
        dropdown: '#boardSelector',
        toggle: '.layui-select-title',
        menu: '[data-role="menu"]',
        trigger: 'click',
        className: {
            hideAnimation: 'layui-anim layui-anim-downbit',
            //showDropdown: 'layui-form-selected',
            //dropdownShow: 'layui-form-selected',
            menuShow: ''
        }
    });

    let boardArr = [];

    if (MixlyUrl.BOARD_CONFIG?.board != undefined) {
        let i = 0;
        for (let key in MixlyUrl.BOARD_CONFIG.board) {
            if (typeof MixlyUrl.BOARD_CONFIG.board[key] == 'object') {
                let j = 0;
                let boardObj = {};
                boardObj.title = key;
                boardObj.id = key;
                boardObj.children = [];
                boardArr.push(boardObj);
                for (let childKey in MixlyUrl.BOARD_CONFIG.board[key]) {
                    let boardObj = {};
                    boardObj.title = childKey;
                    boardObj.id = MixlyUrl.BOARD_CONFIG.board[key][childKey];
                    if (j === 0) {
                        boardObj.checked = true;
                    }
                    boardArr[i].children.push(boardObj);
                    j++;
                }
            } else {
                let boardObj = {};
                boardObj.title = key;
                boardObj.id = MixlyUrl.BOARD_CONFIG.board[key];
                if (i === 0) {
                    boardObj.checked = true;
                }
                boardArr.push(boardObj);
            }
            i++;
        }
    } else {
        let boardObj = {};
        boardObj.title = MixlyUrl.BOARD_CONFIG.boardName;
        boardObj.id = MixlyUrl.BOARD_CONFIG.boardName;
        boardObj.checked = true;
        boardArr.push(boardObj);
    }

    let boardObj = boardArr[0];
    while (typeof boardObj.children === "object") {
        boardObj = boardObj.children[0];
    }

    $input2.val(boardObj.id ? $.trim(boardObj.title) : '');
    instance2.on(instance2.ON_HIDE, function () {
        $("#boardSelector > div > i").css({ 'transform': 'rotate(0deg)', 'top': '50%' });
    });
    instance2.on(instance2.ON_SHOW, function () {
        //tree.reload('demo1');
        $("#boardSelector > div > i").css({ 'transform': 'rotate(180deg)', 'top': '30%' });
        if ($("#boardSelector").find('dl')) {
            $("#boardSelector > dl").css('cssText', "left:" + parseInt(parseInt(($("#boardSelector").width()) - parseInt($("#boardSelector > dl").width())) / 2) + " !important; right:auto !important;");
        }
        $('#board-selecter-tree').find('span').each(function () {
            if (this.innerText === $input2.val()) {
                $(this).css('color', 'red');
            }
            console.log(this.innerText, $input2.val());
        });
    });

    tree.render({
        elem: '#board-selecter-tree',
        data: boardArr,
        id: 'demo1',
        accordion: true,
        click: function (obj) {
            var data = obj.data;
            var value = data.id;
            var text = data.title;

            if (!data.children || !data.children.length) {
                $('#board-selecter-tree').find('span').css('color', '');
                $(obj.elem).find('span').css('color', 'red');
                console.log(value);
                console.log(text);
                $input2.val(value ? $.trim(text) : '');
                instance2.hide();
            }
        }
    });
});
*/

layui.use('form', function () {
    var form = layui.form;
    var boardNames = $('#boards-type');
    if (boardNames) {
        boardNames.empty();
        if (MixlyUrl.BOARD_CONFIG?.board != undefined) {
            for (let key in MixlyUrl.BOARD_CONFIG.board) {
                if (typeof MixlyUrl.BOARD_CONFIG.board[key] == 'object') {
                    let boardStr = `<optgroup label="${key}">`;
                    for (let childKey in MixlyUrl.BOARD_CONFIG.board[key]) {
                        boardStr += `<option value="${MixlyUrl.BOARD_CONFIG.board[key][childKey]}">${childKey}</option>`;
                    }
                    boardStr += `</optgroup>`;
                    boardNames.append(boardStr);
                } else {
                    boardNames.append(`<option value="${MixlyUrl.BOARD_CONFIG.board[key]}">${key}</option>`);
                }
            }
        } else {
            boardNames.append(`<option value="${MixlyUrl.BOARD_CONFIG.boardName}">${MixlyUrl.BOARD_CONFIG.boardName}</option>`);
        }
        form.render();
    }
});

showTag();

function showTag() {
    tagSelect('tab_blocks', 'tab_blocks');
    tagSelect('tab_arduino', 'tab_arduino');
    tagSelect('undo_btn', 'undo');
    tagSelect('redo_btn', 'redo');
    tagSelect('file_btn', 'file');
    tagSelect('new_btn', 'new');
    tagSelect('open_btn', 'open');
    tagSelect('save_btn', 'save');
    tagSelect('connect_btn', 'connect');
    tagSelect('download_btn', 'upload');
    tagSelect('upload_btn', 'upload');
    tagSelect('save_xml_btn', 'save_blocks');
    tagSelect('save_ino_btn', 'save_ino');
    tagSelect('save_img_btn', 'save_img');
    tagSelect('save_py_btn', 'save_py');
    tagSelect('save_hex_btn', 'save_hex');
    tagSelect('save_as_btn', 'save_as');
    tagSelect('setting_btn', 'setting');
    tagSelect('language_btn', 'language');
    tagSelect('theme_btn', 'theme');
    if (document.getElementById('changemod_btn') 
        && document.getElementById('changemod_btn').value == 0) {
        tagSelect('changemod_btn', 'tab_blocks');
    } else {
        tagSelect('changemod_btn', 'tab_arduino');
    }
    tagSelect('serial_read_btn', 'catSerialPort');
    tagSelect('serial_reset', 'serial_reset');
    tagSelect('arduino_compile_btn', 'compile');
    tagSelect('arduino_download_btn', 'upload');
    tagSelect('layer_btn', 'status_bar_show');
    if (document.getElementById('boardSelector'))
        document.getElementById('boardSelector').placeholder = MSG['fn'];
    tagSelect('play_btn', 'run');
    tagSelect('stop_btn', 'stop');

    tagSelect('operate_undo_btn', 'undo');
    tagSelect('operate_redo_btn', 'redo');
    tagSelect('operate_connect_btn', 'connect');
    tagSelect('operate_upload_btn', 'upload');
    tagSelect('operate_download_btn', 'upload');
    tagSelect('operate_serial_read_btn', 'catSerialPort');
    tagSelect('operate_serial_reset', 'serial_reset');
    tagSelect('operate_arduino_compile', 'compile');
    tagSelect('operate_download_btn', 'upload');
    tagSelect('operate_layer_btn', 'status_bar_show');
    tagSelect('operate_btn', 'operate');
    tagSelect('operate_save_ser_btn', 'save_ser');
    tagSelect('import_libraries_btn', 'import_libraries');
    tagSelect('manage_libraries_btn', 'manage_libraries');
    tagSelect('windows_size_btn', 'windowSize');
    tagSelect('change_board_btn', 'change_board');
    tagSelect('simulate_btn', 'simulate');
    tagSelect('operate_simulate_btn', 'simulate');
    tagSelect('view_btn', 'view_btn');
    tagSelect('save_ser_btn', 'save_ser');
    tagSelect('view_file', 'view_file');
    tagSelect('operate_play_btn', 'run');
    tagSelect('operate_stop_btn', 'stop');
}

function tagSelect(id, msg) {
    var tagObject = document.getElementById(id);
    if (tagObject) {
        if (tagObject.tagName == "A" && tagObject.parentNode.innerHTML.indexOf("<dl") != -1) {
            tagObject.innerHTML = MSG[msg] + "<span class=\"layui-nav-more\"></span>";
        } else {
            document.getElementById(id).innerHTML = MSG[msg];
        }
    }
}
